package com.aplink.generic.adapter;

import java.util.ArrayList;

import android.text.TextUtils;
import android.widget.Filter;

import com.aplink.generic.pojo.GenericObject;

public class AdapterFilter extends Filter {
	private final ConfigAdapter mConfigAdapter;
	private final ArrayList<String> mSearchFileds;

	public AdapterFilter(final ArrayList<String> searchFileds,
	        final ConfigAdapter configAdapter) {
		mSearchFileds = searchFileds;
		mConfigAdapter = configAdapter;
	}

	public ArrayList<String> getSearchFileds() {
		return mSearchFileds;
	}

	@Override
	protected FilterResults performFiltering(final CharSequence constraint) {
		final FilterResults filterResults = new FilterResults();
		final ArrayList<GenericObject> filteredArrList = new ArrayList<GenericObject>();
		if (TextUtils.isEmpty(constraint)) {
			filterResults.values = mConfigAdapter.getOriginalObjects();
			filterResults.count = mConfigAdapter.getOriginalObjects().size();
		} else {
			for (final GenericObject genericObject : mConfigAdapter
			        .getOriginalObjects()) {
				if (genericObject
				        .contains(constraint.toString(), mSearchFileds)) {
					filteredArrList.add(genericObject);
				}
			}
			filterResults.count = filteredArrList.size();
			filterResults.values = filteredArrList;
		}
		return filterResults;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void publishResults(final CharSequence constraint,
	        final FilterResults results) {
		mConfigAdapter
		        .setDisplayObjects((ArrayList<GenericObject>) results.values);
	}
}
